package net.wangxl.miaosha.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Primary
@Service("miaoshaService")
public class MiaoshaServiceImpl implements MiaoshaService{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init(){
        stringRedisTemplate.delete("tokenList");
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        //初始化令牌桶(实际上也是利用队列的性质进行过滤)
        for(int i=0;i<10;i++){
            opsForList.leftPush("tokenList", String.valueOf(i));
        }
    }
    @Override
    public boolean miaosha(String userId) {
        if(StringUtils.isEmpty(userId))
            return false;
        //秒杀的步骤

        //1.对于点击过于频繁的用户，要限制其频率
        ValueOperations<String, String> opsValue = stringRedisTemplate.opsForValue();
        Boolean res = opsValue.setIfAbsent(userId, "1",2, TimeUnit.SECONDS);
        if(!res){
            System.out.println(userId+"点击频率过高，被拒绝秒杀");
            return false;
        }
        //2.使用令牌桶提前进行过滤，防止过多请求打入数据库（此过程基本会确定秒杀的结果）
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        String token = opsForList.leftPop("tokenList");
        if(StringUtils.isEmpty(token)){
            System.out.println(userId+"获取token失败，被拒绝秒杀");
            return false;
        }
        System.out.println(userId+"获取token成功，可以参与秒杀");

        //3.进行数据库的秒杀操作（实际上就是入库操作）
        return false;
    }
}
